{include file="Public:header2"/}
<body style="min-height: 100%;background-color: #fff">

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form onsubmit="return false;">
                        <div class="layui-form" wid100 lay-filter="">
                            <div class="layui-form-item">
                                <label class="layui-form-label">分类</label>
                                <div class="layui-input-inline cate1">
                                    <select name="cate_id" lay-verify="" lay-filter="choose">
                                        <option value="">--请选择一级分类--</option>
                                        {foreach name="cate" item="vo"}
                                            <option {if condition="$data['cate_id'] eq $vo['id']"} selected {/if} value="{$vo.id}">{$vo.title}</option>
                                        {/foreach}
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="title" value="{$data['title']}" lay-verify="required" placeholder="请输入商品名称" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" lay-filter="">
                                <label class="layui-form-label">状态</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="status" value="1" title="上架" {if condition="$data['status'] eq 1"} checked {/if}>
                                    <input type="radio" name="status" value="2" title="下架" {if condition="$data['status'] eq 2"} checked {/if}>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品封面图</label>
                                <div class="layui-input-inline">
                                    <input type="hidden" name="imgurl" value="{$data['imgurl']}" lay-verify="required" placeholder="请上传图片" autocomplete="off" class="layui-input" >
                                    <img style="float:left;width:120px;" class="" id="imgurl" src="{PHP} echo imageUrl($data['imgurl']){/php}">
                                </div>
                                <div class="layui-form-mid layui-word-aux">提示：建议最大不超过1M，格式为：.jpg，.jpeg，.png</div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品轮播图</label>
                                <div class="layui-input-block imgs">
                                    <div class=" layui-word-aux">提示：建议最大不超过1M，格式为：.jpg，.jpeg，.png(点击图片删除)</div>

                                    <input type="hidden" name="imgurls"  class="imgss" value="{$data['imgurls']}" lay-verify="required" placeholder="请上传图片" autocomplete="off" class="layui-input">
                                    <img style="width:120px;" class="" id="imgs" src="/static/admin/style/res/upload.jpg">
                                    {volist name="imgurls" id="v"}
                                        <img style="width:120px;" onclick="del(this)" class="" id="imgs" data-imgurl="{$v}" src="{PHP} echo imageUrl($v){/php}">
                                    {/volist}
                                </div>                                    
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">排序值</label>
                                <div class="layui-input-inline">
                                    <input type="number" name="sort" value="{$data['sort']}" lay-verify="required" placeholder="请输入排序值" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" lay-filter="">
                                <label class="layui-form-label">是否可退</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="is_tui" value="1" title="是" {if condition="$data['is_tui'] eq 1"} checked {/if}>
                                    <input type="radio" name="is_tui" value="2" title="否" {if condition="$data['is_tui'] eq 2"} checked {/if}>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品运费</label>
                                <div class="layui-input-inline">
                                    <input type="number" name="yunfei" value="{$data['yunfei']}" lay-verify="required" placeholder="请输入商品运费（0为包邮）" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-form-item" lay-filter="">
                                <label class="layui-form-label">规格属性</label>
                                <div class="layui-input-block norms_type">
                                    <input type="radio" name="norms_type" value="1" title="单规格" {if condition="$data['norms_type'] eq 1"} checked {/if}>
                                    <input type="radio" name="norms_type" value="2" title="多规格" {if condition="$data['norms_type'] eq 2"} checked {/if}>
                                </div>
                            </div>
                            <!-- 单规格开始-->
                            <div id="no_norms" {if condition="$data['norms_type'] eq 2"} style="display:none"{/if}>
                                <div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label"></label>
                                        <div class="layui-input-block">
                                            <table class="layui-table">
                                                <thead>
                                                <tr>
                                                    <th>图片</th>
                                                    <th>售价</th>
                                                    <th style='display: none;'>原价</th>
                                                    <th>库存</th>
                                                </tr>
                                                </thead>
                                                <tr>
                                                    <td>
                                                        <input type="hidden" name="attr_imgurl" value="{$product_norms_value[0]['imgurl']}" class="layui-input">
                                                        <img style="width:40px;" id="sku_img" src="{PHP} echo imageUrl($product_norms_value[0]['imgurl']){/php}" >
                                                    </td>
                                                    <td>
                                                        <input type="text" name="attr_price" value="{$data['price']}" class="layui-input">
                                                    </td>
                                                    <td style="display:none;">
                                                        <input type="text" name="attr_old_price"  value="{$data['old_price']}" class="layui-input">
                                                    </td>
                                                    <td>
                                                        <input type="text" name="attr_stock" value="{$data['stock']}" class="layui-input">
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- 单规格结束-->

                            <!-- 多规格-->
                            <div id="yes_norms" {if condition="$data['norms_type'] eq 1"} style="display:none"{/if}>
                                <div >
                                    <div class="control-group layui-form-item">
                                        <label class="control-label layui-form-label"> </label>
                                        <div class="controls">
                                            <button id="add_lv1" class="btn btn-primary layui-btn layui-btn-sm" type="button">添加规格项</button>
                                            <button id="update_table" class="btn btn-success layui-btn layui-btn-sm update_table2" type="button" lay-active="e1">生成规格项目表</button>
                                        </div>
                                    </div>
                                        {foreach name="product_norms" item="vo" key="k"}
                                            <div class="control-group lv1 layui-form-item">
                                                <label class="control-label layui-form-label">规格名称</label>
                                                <div class="controls layui-input-block">
                                                    <input type="text" name="lv1[]" value="{$vo['norms_name']}" style="height: 30px;line-height:30px;margin-right:8px" placeholder="规格名称">
                                                    <button class="btn btn-primary add_lv2 layui-btn layui-btn-sm" type="button">添加属性</button>
                                                    <button class="btn btn-danger remove_lv1 layui-btn layui-btn-sm" type="button">删除规格</button>
                                                </div>
                                                <div class="controls lv2s">
                                                    {volist name="vo['norms_values']" id="voo"}
                                                    <div style="margin-top: 5px;margin-left:150px">
                                                        <input type="text" name="lv2[{$k}][]" value="{$voo}" style="height: 25px;line-height:25px;margin-right:8px" placeholder="属性名称">
                                                        <button class="btn btn-danger remove_lv2 layui-btn layui-btn-sm" type="button">删除属性</button>
                                                    </div>
                                                    {/volist}
                                                </div>
                                            </div>
                                        {/foreach}
                                    <div id="lv_table_con" class="control-group layui-form-item" style="display: none;">
                                        <label class="control-label layui-form-label">商品属性：</label>
                                        <div class="controls">
                                            <div id="lv_table" class="layui-input-block">
                                                
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- 多规格结束-->

                            <div class="layui-form-item">
                                <label class="layui-form-label">商品详情</label>
                                <div class="layui-input-block" >
                                    <script type="text/plain" name="content" id="editor" style="height:400px;">{$data['content']|raw}</script>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <input type="hidden" name="id" value="{$data['id']}">
                                    <button class="layui-btn" onclick="return check()">确认保存</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
{include file="Public:footer"/}
</body>
</html>
<input type="hidden" name="my_id" value="" id="my_id">
<script type="text/javascript" src="/static/admin/lib/ueditor/1.4.3/ueditor.config.js"></script>
<script type="text/javascript" src="/static/admin/lib/ueditor/1.4.3/ueditor.all.min.js"> </script>
<script type="text/javascript" src="/static/admin/lib/ueditor/1.4.3/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">
    layui.use(['layer','form','upload','laydate','util'], function(){
        var $ = layui.$;
        $(function(){
            var ue = UE.getEditor('editor');
        })
        var upload = layui.upload;
        var form = layui.form;
        var util = layui.util;
        //执行实例
        var uploadInst = upload.render({
            accept:'imgurl'
            ,elem: '#imgurl' //绑定元素
            ,url: '/admin/picture' //上传接口
            ,done: function(res){
                //上传完毕回调
                if(res.status == 1){ //成功
                    layer.msg("上传成功",{icon:1,time:1000},function(){
                        $("#imgurl").attr("src",res.data.path);  //单图
                        $("input[name=imgurl]").val(res.data.imgurl);
                    });
                }else{ //失败
                    layer.msg(res.msg,{icon:2,anim:6,time:1500});
                }
            }
            ,error: function(){
                //请求异常回调
                layer.msg('服务繁忙，请稍后再试',{icon:2,anim:6,time:1500});
            }
        });

            //执行实例   //上传多图
            var uploadInst = upload.render({
                accept:'imgs'
                ,elem: '#imgs' //绑定元素
                ,url: '/admin/picture' //上传接口
                ,done: function(res){
                    //上传完毕回调
                    if(res.status == 1){ //成功
                        layer.msg("上传成功",{icon:1,time:1000},function(){
                            var ml = '<img style="width:120px;margin-left:2px;" onclick="del(this)" class="" data-imgurl="'+res.data.imgurl+'" src="'+res.data.path+'">';
                            $(".imgs").append(ml);
                            var imgs=$("input[name=imgurls]").val();
                            imgs=imgs+','+res.data.imgurl;
                            $("input[name=imgurls]").val(imgs);
                        });
                    }else{ //失败
                        layer.msg(res.msg,{icon:2,anim:6,time:1500});
                    }
                }
                ,error: function(){
                    //请求异常回调
                    layer.msg('服务繁忙，请稍后再试',{icon:2,anim:6,time:1500});
                }
            });


           //单规格图片
        var uploadInst = upload.render({
            accept:'sku_img'
            ,elem: '#sku_img' //绑定元素
            ,url: '/admin/picture' //上传接口
            ,done: function(res){
                //上传完毕回调
                if(res.status == 1){ //成功
                    layer.msg("上传成功",{icon:1,time:1000},function(){
                        $("#sku_img").attr("src",res.data.path);  //单图
                        $("input[name=attr_imgurl]").val(res.data.imgurl);
                    });
                }else{ //失败
                    layer.msg(res.msg,{icon:2,anim:6,time:1500});
                }
            }
            ,error: function(){
                //请求异常回调
                layer.msg('服务繁忙，请稍后再试',{icon:2,anim:6,time:1500});
            }
        });

        util.event('lay-active', {
            e1: function(){
                setTimeout(function(){
                    //规格图片
                var uploadInst = upload.render({
                    accept:'sku_imgurl'
                    ,elem: '.sku_imgurl' //绑定元素
                    ,url: '/admin/picture' //上传接口
                    ,before:function(a){ 
                        var id = this.id;
                        $('#my_id').val(id);
                    }
                    ,done: function(res){
                        //上传完毕回调
                        if(res.status == 1){ //成功
                            id = $('#my_id').val();
                            layer.msg("上传成功",{icon:1,time:1000},function(){
                                $("#sku_imgurl"+id).val(res.data.imgurl);  //单图
                                $(".sku_imgurl"+id).attr("src",res.data.path);
                            });
                            
                        }else{ //失败
                            layer.msg(res.msg,{icon:2,anim:6,time:1500});
                        }
                    }
                    ,error: function(){
                        //请求异常回调
                        layer.msg('服务繁忙，请稍后再试',{icon:2,anim:6,time:1500});
                    }
                });
                },500);
            }
        });

        

        //开启规格
        $(".norms_type").click(function(){
            var val = $('input[name=norms_type]:checked').val();
            if(val == 1){
                $("#yes_norms").hide();
                $("#no_norms").show();
            }else{
                $("#yes_norms").show();
                $("#no_norms").hide();
            }
        });

        //规格
        var lv1HTML = '<div class="control-group lv1 layui-form-item">' +
            '<label class="control-label layui-form-label">规格名称</label>' +
            '<div class="controls layui-input-block">' +
            '<input type="text" name="lv1[]" style="height: 30px;line-height:30px;margin-right:8px" placeholder="规格名称">' +
            '<button class="btn btn-primary add_lv2 layui-btn layui-btn-sm" type="button">添加属性</button>' +
            '<button class="btn btn-danger remove_lv1 layui-btn layui-btn-sm" type="button">删除规格</button>' +
            '</div>' +
            '<div class="controls lv2s"></div>' +
            '</div>';

        $('#add_lv1').on('click', function() {
            var last = $('.control-group.lv1:last');
            if (!last || last.length == 0) {
                $(this).parents('.control-group').eq(0).after(lv1HTML);
            } else {
                last.after(lv1HTML);
            }
        });

        $(document).on('click', '.remove_lv1', function() {
            $(this).parents('.lv1').remove();
        });

        $(document).on('click', '.add_lv2', function() {
            var inx1 = $('.add_lv2').index(this);
            var name = "lv2["+inx1+"][]";
            var lv2HTML2 = '<div style="margin-top: 5px;margin-left:150px">' +
                '<input type="text" name="'+name+'" style="height: 25px;line-height:25px;margin-right:8px" placeholder="属性名称">' +
                '<button class="btn btn-danger remove_lv2 layui-btn layui-btn-sm" type="button">删除属性</button>' +
                '</div>';

            $(this).parents('.lv1').find('.lv2s').append(lv2HTML2);
        });

        $(document).on('click', '.remove_lv2', function() {
            $(this).parent().remove();
        });

        $('#update_table').on('click', function() {
            get_format_attr(1);
        });
        var norms_type = $('input[name=norms_type]:checked').val();
        if(norms_type == 2){
            get_format_attr(0);
            setTimeout(function(){
                $('.update_table2').trigger('click');
            },800);
            // get_format_attr(0);
        }
    });

    //点击图片删除
    Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };

    Array.prototype.rem = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    function del(o){
        var $ = layui.$;
        var img = $(o).attr("data-imgurl");
        layer.confirm("确定删除吗？",function(index){
            var imgs = $('.imgss').val();
            ss = imgs.split(",");
            ss.rem(img);
            ss.join(",");
            $('.imgss').val(ss);
            $(o).remove();
            layer.closeAll('dialog');
        });
    }

    //获取属性
    function get_format_attr(type){
        var url="{:url('/admin/product_get_format_attr')}";
        var $ = layui.$;
        var form = layui.form;
        var load=layer.load(2);
        var product_id = $('input[name=id]').val();
        var lv1 = [];
        var lv2 = [];
        $('input[name="lv1[]"]').each(function(index,element){
            //压入数组
            lv1.push($(this).val());
            var data_arr_detail = [];
            $('input[name="lv2['+index+'][]"]').each(function(index2,element2){
                data_arr_detail[index2] = $(this).val();
            })
            lv2.push(data_arr_detail);
        });

        //console.log(lv1);
        //console.log(lv2);
        var lv1_json = JSON.stringify(lv1);
        var lv2_json = JSON.stringify(lv2);
        //console.log(lv1_json);
        //console.log(lv2_json);
        $.post(url,{'product_id':product_id,'type':type,'lv1_json':lv1_json,'lv2_json':lv2_json},function(data){
            console.log(data);
            if(data.status == 1){
                $('#lv_table').empty();   //清空标签里面的所有内容
                var tableHtml = '';
                tableHtml += '<table class="table table-bordered layui-table">';
                tableHtml += '  <thead>';
                tableHtml += '      <tr>';
                $.each(data.data.header, function(commentIndex, comment){
                    tableHtml += '          <th width="'+comment['width']+'">'+comment['title']+'</th>';
                });
                tableHtml += '      </tr>';
                tableHtml += '  </thead>';
                tableHtml += '  <tbody>';
                $.each(data.data.value, function(commentIndex, comment){
                    tableHtml += '      <tr data-row="'+commentIndex+'">';
                    $.each(data.data.attr, function(commentIndex2, comment2){
                        tableHtml += '          <td width="50" rowSpan="" data-rc="">'+comment['value'+commentIndex2]+'</td>';
                    })

                    tableHtml += '          <td width="20">';
                    tableHtml += '              <input type="hidden" class="layui-input" id="sku_imgurl'+commentIndex+'"  name="attr_value['+commentIndex+'][imgurl]" value="'+comment['imgurl']+'"><img style="width:40px;" class="sku_imgurl sku_imgurl'+commentIndex+'" src="'+comment['imgurls']+'" lay-data="{id:'+commentIndex+'}">';
                    tableHtml += '          </td>';
                    tableHtml += '          <td width="20">';
                    tableHtml += '              <input type="text" class="layui-input" name="attr_value['+commentIndex+'][price]" value="'+comment['price']+'">';
                    tableHtml += '          </td>';
                    tableHtml += '          <td width="20" style="display:none;">';
                    tableHtml += '              <input type="text" class="layui-input" name="attr_value['+commentIndex+'][old_price]" value="'+comment['old_price']+'">';
                    tableHtml += '          </td>';
                    tableHtml += '          <td width="20">';
                    tableHtml += '              <input type="text" class="layui-input" name="attr_value['+commentIndex+'][stock]" value="'+comment['stock']+'">';
                    tableHtml += '          </td>';
                    tableHtml += '          <td width="20" style="display: none;">';
                    tableHtml += '              <input type="hidden" name="attr_value['+commentIndex+'][sku]" value="'+comment['detail']+'">';
                    tableHtml += '          </td>';
                    tableHtml += '      </tr>';
                });
                tableHtml += '  </tbody>';
                tableHtml += '</table>';
                $('#lv_table').html(tableHtml);
                $('#lv_table_con').show();
                form.render();
                layer.close(load);
            }else{
                layer.msg(data.msg,{icon:2,anim:6,time:1500},function(){
                    layer.close(load);
                });
            }
        })
    }

    function check(){
        var url="{:url('/admin/product_edit')}";
        var $ = layui.$;
        var load=layer.load(2);
        $.post(url,$("form").serialize(),function(data){
            if(data.status==1){
                layer.msg(data.msg,{icon:1,time:1500},function(){
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index);
                    parent.location.reload();
                });
            }else{
                layer.msg(data.msg,{icon:2,anim:6,time:1500},function(){
                    layer.close(load);
                });
            }
        })
    }
</script>